package top.zlhy7.interceptor;

import com.github.lianjiatech.retrofit.spring.boot.interceptor.BasePathMatchInterceptor;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author 任勇
 * @date 2021/12/22 17:21
 * @description 给指定请求的url后面拼接timestamp时间戳为例
 */
@Component
public class TimeStampInterceptor extends BasePathMatchInterceptor {
    @Override
    protected Response doIntercept(Chain chain) throws IOException {
        Request request = chain.request();
        HttpUrl url = request.url();
        long timestamp = System.currentTimeMillis();
        //给url添加query参数时间戳
        HttpUrl newUrl = url.newBuilder()
                .addQueryParameter("timestamp", String.valueOf(timestamp))
                .build();
        //给header添加东西
        Headers oldHeaders = request.headers();
        Headers.Builder headersBuilder = new Headers.Builder()
                .addAll(oldHeaders)
                .add("token","123456");
        Request newRequest = request.newBuilder()
                .url(newUrl)
                .headers(headersBuilder.build())
                .build();
        return chain.proceed(newRequest);
    }
}
